package com.qianguo.shop.activity;

import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.TimePicker;

import com.eva.androidlibrary.api.HttpRequestCallback;
import com.eva.androidlibrary.api.entity.ImageBean;
import com.eva.androidlibrary.api.entity.ResultData;
import com.eva.androidlibrary.utils.ValidateUtil;
import com.eva.androidlibrary.widget.LayerMaskPopupWindow;
import com.eva.androidlibrary.widget.mdedittext.MaterialEditText;
import com.qianguo.shop.R;
import com.qianguo.shop.base.BaseChooseImageActivity;
import com.qianguo.shop.constant.ShopKeys;
import com.eva.androidlibrary.api.entity.ShopInfo;

import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Extra;
import org.androidannotations.annotations.ViewById;
import org.greenrobot.eventbus.EventBus;

import java.io.File;


/**
 * 添加水果店
 *
 * @author eva
 * @date 2015-11-17 05:24
 */
@EActivity(R.layout.activity_shop_add)
public class AddOrEditShopActivity extends BaseChooseImageActivity {
    
    /** 水果店名称 */
    @ViewById(R.id.shop_add_name_edit_text)
    MaterialEditText mEdtName;

    /** 水果店联系方式 */
    @ViewById(R.id.shop_add_mobile_edit_text)
    MaterialEditText mEdtMobile;

    /** 水果店地址 */
    @ViewById(R.id.shop_add_address_tv)
    TextView mTvAddress;

    /** 水果店营业时间 */
    @ViewById(R.id.shop_add_open_time_tv)
    TextView mTvOpenTime;

    /** 水果店简介 */
    @ViewById(R.id.shop_add_introduction_edit_text)
    EditText mEdtIntro;

    /** 水果店图片 */
    @ViewById(R.id.shop_add_picture_image_view)
    ImageView mImgPicture;

    @Extra(ShopKeys.EXTRA_KEY_SHOP_INFO)
    ShopInfo mShopInfo;

    @Extra(ShopKeys.EXTRA_KEY_SHOP_LONGITUDE)
    String mShopLongitude;

    @Extra(ShopKeys.EXTRA_KEY_SHOP_LATITUDE)
    String mShopLatitude;

    private LayerMaskPopupWindow mPopupWindow;
    private TimePicker mStartTimePicker;
    private TimePicker mEndTimePicker;
    private String mPicFilePath;

    private int mStartHour = 9;
    private int mStartMinute = 0;
    private int mEndHour = 21;
    private int mEndMinute = 0;

    public static void jumpToAddOrEditShop(Context context, ShopInfo shopInfo) {
        Intent intent = new Intent();
        intent.putExtra(ShopKeys.EXTRA_KEY_SHOP_INFO, shopInfo);
        intent.setClass(context, com.qianguo.shop.activity.AddOrEditShopActivity_.class);
        context.startActivity(intent);
    }

    @Override
    protected String getToolbarTitle() {
        return getString(R.string.shop_add_title);
    }

    @Override
    protected void initializeUI() {
        if (mShopInfo != null) {
            mEdtName.setText(mShopInfo.getName());
            mTvAddress.setText(mShopInfo.getAddress());
            mEdtMobile.setText(mShopInfo.getMobile());
            mEdtIntro.setText(mShopInfo.getIntro());
            mTvOpenTime.setText(mShopInfo.getOpenTime());
            mImageLoader.loadImage(this, mImgPicture, mShopInfo.getLogo());
        } else {
            mShopInfo = new ShopInfo();
        }

        if (!TextUtils.isEmpty(mShopLatitude)) {
            mShopInfo.setLongitude(mShopLongitude);
        }

        if (!TextUtils.isEmpty(mShopLatitude)) {
            mShopInfo.setLatitude(mShopLatitude);
        }
    }

    @Click(R.id.shop_add_open_time_tv)
    void clickOpenTime() {
        if (mPopupWindow == null) {
            View v = LayoutInflater.from(this).inflate(R.layout.layout_shop_add_choose_open_time, null);
            mStartTimePicker = (TimePicker) v.findViewById(R.id.start_time_picker);
            mEndTimePicker = (TimePicker) v.findViewById(R.id.end_time_picker);
            mStartTimePicker.setIs24HourView(true);
            mEndTimePicker.setIs24HourView(true);
            mStartTimePicker.setOnTimeChangedListener(mOnStartTimeChangedListener);
            mEndTimePicker.setOnTimeChangedListener(mOnEndTimeChangedListener);
            // 禁止通过软键盘输入
            mStartTimePicker.setDescendantFocusability(TimePicker.FOCUS_BLOCK_DESCENDANTS);
            mEndTimePicker.setDescendantFocusability(TimePicker.FOCUS_BLOCK_DESCENDANTS);
            mPopupWindow = new LayerMaskPopupWindow(this, mOnDismissListener);
            mPopupWindow.setContentView(v);
        }

        if (mPopupWindow.isShowing()) {
            return;
        }

        mStartTimePicker.setCurrentHour(mStartHour);
        mStartTimePicker.setCurrentMinute(mStartMinute);

        mEndTimePicker.setCurrentHour(mEndHour);
        mEndTimePicker.setCurrentMinute(mEndMinute);

        mPopupWindow.showAtLocation(getWindow().getDecorView(), Gravity.CENTER, 0, 0);
    }

    private PopupWindow.OnDismissListener mOnDismissListener = new PopupWindow.OnDismissListener() {
        @Override
        public void onDismiss() {
            String startMinute = String.valueOf(mStartMinute);
            String endMinute = String.valueOf(mEndMinute);
            if (mStartMinute < 10) {
                startMinute = "0" + startMinute;
            }

            if (mEndMinute < 10) {
                endMinute = "0" + endMinute;
            }
            mTvOpenTime.setText(mStartHour + ":" + startMinute + " - " + mEndHour + ":" + endMinute);
        }
    };

    private TimePicker.OnTimeChangedListener mOnStartTimeChangedListener = new TimePicker.OnTimeChangedListener() {
        @Override
        public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
            mStartHour = hourOfDay;
            mStartMinute = minute;
        }
    };

    private TimePicker.OnTimeChangedListener mOnEndTimeChangedListener = new TimePicker.OnTimeChangedListener() {
        @Override
        public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
            mEndHour = hourOfDay;
            mEndMinute = minute;
        }
    };

    @Background
    @Click(R.id.shop_add_submit_button)
    void clickSubmit() {
        String name = mEdtName.getText().toString();
        String mobile = mEdtMobile.getText().toString();
        String serviceTime = mTvOpenTime.getText().toString();
        String intro = mEdtIntro.getText().toString();

        if (validateInfo(name, mobile, serviceTime, intro)) {
            mShopInfo.setName(name);
            mShopInfo.setMobile(mobile);
            mShopInfo.setOpenTime(serviceTime);
            mShopInfo.setIntro(intro);

            showLoadingDialog(this);
            if (!TextUtils.isEmpty(mPicFilePath)) {
                uploadImage();
            } else {
                submitShopInfo(mShopInfo);
            }
        }
    }

    /**
     * 上传店铺图片
     */
    void uploadImage() {
        mApp.getApi().uploadImg(mApp.getUser().getToken(), new File(mPicFilePath), new HttpRequestCallback<ImageBean>() {
            @Override
            public void onSuccess(int code, String msg, ImageBean data) {
                mShopInfo.setLogo(data.getUrl());
                submitShopInfo(mShopInfo);
            }

            @Override
            public void onFailure(int code, String msg) {
                showSnackBar(AddOrEditShopActivity.this, msg);
                closeLoadingDialog();
            }
        });
    }

    /**
     * 编辑店铺信息
     * @param shop
     */
    void submitShopInfo(final ShopInfo shop) {
        if (TextUtils.isEmpty(shop.getId())) {
            addShopInfo(shop);
        } else {
            editShopInfo(shop);
        }

        closeLoadingDialog();
    }

    void editShopInfo(final ShopInfo shop) {
        mApp.getApi().editShopInfo(mApp.getUser().getToken(), shop, new HttpRequestCallback<ResultData>() {
            @Override
            public void onSuccess(int code, String msg, ResultData data) {
                showSnackBar(AddOrEditShopActivity.this, msg);
                EventBus.getDefault().post(shop);
                finish();
            }

            @Override
            public void onFailure(int code, String msg) {
                showSnackBar(AddOrEditShopActivity.this, msg);
            }
        });
    }

    void addShopInfo(final ShopInfo shop) {
        mApp.getApi().addShop(mApp.getUser().getToken(), shop, new HttpRequestCallback<ShopInfo>() {
            @Override
            public void onSuccess(int code, String msg, ShopInfo data) {
                showSnackBar(AddOrEditShopActivity.this, msg);
                EventBus.getDefault().post(shop);
                finish();
            }

            @Override
            public void onFailure(int code, String msg) {
                showSnackBar(AddOrEditShopActivity.this, msg);
            }
        });

    }

    @Click(R.id.shop_add_picture_image_view)
    void clickChoosePic() {
        showPickerDialog(new PicPickerCallback() {
            @Override
            public void afterPick(String filePath) {
                mPicFilePath = filePath;
                mImageLoader.loadImage(AddOrEditShopActivity.this, mImgPicture, filePath);
            }
        });
    }


    private boolean validateInfo(String name, String mobile, String serviceTime, String intro) {
        if (TextUtils.isEmpty(name)) {
            mEdtName.setError(getString(R.string.shop_add_error_name));
            return false;
        }

        if (!ValidateUtil.isChinesePhoneNumber(mobile)) {
            mEdtMobile.setError(getString(R.string.edit_error_mobile));
            return false;
        }

        if (TextUtils.isEmpty(serviceTime)) {
            showSnackBar(this, getString(R.string.shop_add_error_service_time));
            return false;
        }

        if (TextUtils.isEmpty(intro)) {
            mEdtIntro.setError(getString(R.string.shop_add_error_intro));
            return false;
        }
        return true;
    }

}
